<?php
/**
 * Created by PhpStorm.
 * User: Thanh Lâm
 * Date: 5/15/14
 * Time: 10:50 AM
 */
namespace Phalconvn\Email;


use Phalcon\Mvc\User\Component;
use Apps\Backend\Models\EmailTemplate;
use Apps\Backend\Models\EmailError;
//load template email
class Send  extends Component {
    public function email($template,$data,$content=null,$attack=null){
       require_once 'lib/PHPMailerAutoload.php';
        $mail = new \PHPMailer();
        $mail->isSMTP();
        $mail->SMTPDebug  = 2;// Set mailer to use SMTP
        $mail->Host = '112.213.86.227';  // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Port = 25;
        $templateEmail = EmailTemplate::findFirst(array('conditions'=>"alias = ?1 AND status = 1",
                                                         'bind'=>array(1=>$template)));
        //lay thông tin gui
        $mail->Username = $templateEmail->email->email;                 // SMTP username
        $mail->Password = $templateEmail->email->password;                           // SMTP password
        $mail->SMTPSecure = 'tls';
        //thông tin nguoi gửi
        $mail->SetFrom($templateEmail->email->email,$templateEmail->email->name);
        //email người nhận
        $mail->addAddress($data['email'], $data['first_name'].' '. $data['name']);
        $mail->AddReplyTo($templateEmail->email->email,$templateEmail->email->name);

        //noi dung email
        $template = $templateEmail->content;
        foreach($content as $key => $val){
            $template = str_replace($key,$val,$template);
        }
        $mail->Subject = $templateEmail->name;
        $mail->CharSet = "utf-8";
        $mail->MsgHTML = $template;
        $mail->msgHTML($template);

        if(!$mail->Send()) {
            $tbEmailError = new EmailError();
            $tbEmailError->save(array('active_code'=>$data['active_code'],'template'=>$template,'status'=>'0','created'=>time()));
        }
    }
}